import requests
import datetime
import csv
import json
import os


def open_csv():
    if os.path.exists("../../static/csv/today.csv"):  # 如果文件存在
        # 删除文件，可使用以下两种方法。
        os.remove('../../static/csv/today.csv')  # 则删除
    with open('../../static/csv/today.csv', 'w', newline='', encoding='utf-8') as file:
        csv.writer(file).writerow(['province', 'today_confirm' ,'now_confirm', 'confirm', 'dead', 'heal', 'dead_rate', 'heal_rate'])


def write_csv(x1, x2, x3, x4, x5, x6, x7, x8):
    with open('../../static/csv/today.csv', 'a', newline='', encoding='utf-8') as file:
        csv.writer(file).writerow([x1, x2, x3, x4, x5, x6, x7, x8])


def get_data():
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_='+str(datetime.datetime.now().microsecond)
    response = requests.get(url)
    data = json.loads(response.json()['data'])
    china_data = data['areaTree'][0]['children']

    open_csv()
    for t in china_data:
        # 省份
        province = t['name']
        #今日确诊
        today_confirm = t['today']['confirm']
        # 现存确诊
        now_confirm = t['total']['nowConfirm']
        # 累计确诊人数
        confirm = t['total']['confirm']
        # 死亡人数
        dead = t['total']['dead']
        # 治愈人数
        heal = t['total']['heal']
        # 死亡率
        dead_rate = t['total']['deadRate']
        # 治愈率
        heal_rate = t['total']['healRate']
        write_csv(province, today_confirm, now_confirm, confirm, dead, heal, dead_rate, heal_rate)


get_data()
